package com.wang.servlet;

import com.alibaba.fastjson.JSON;
import com.wang.utils.ConstantsUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author wr
 * @date 2021/10/29 10:52
 */
@WebServlet(name = "getFileList", urlPatterns = ConstantsUtil.Home.ROOT_PATH + ConstantsUtil.Home.GET_FILE_LIST)
public class GetFileList extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String user = (String) req.getSession().getAttribute(ConstantsUtil.Login.USER_KEY);
        String storagePath = req.getServletContext().getRealPath(ConstantsUtil.Storage.STORAGE_ROOT);
        File file = new File(storagePath + user);
        List<String> names = new ArrayList<>();
        System.out.println(storagePath + user);
        if (file.exists()) {
            System.out.println("fileExist");
            for (File f : Objects.requireNonNull(file.listFiles())) {
                names.add(f.getName());
            }
            System.out.println(names.toString());
        }
        resp.getWriter().write(JSON.toJSONString(names));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
}
